package com.yuyue.note02.controller;

import com.yuyue.note01.entity.User;
import com.yuyue.note02.error.BusinessException;
import com.yuyue.note02.error.ProjectErrorCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@Controller
//@ResponseBody 上述两个注解可以合并为RESTful风格的 @RestController
@RestController
//所有的方法都有 @RequestMapping，因此提前到类上
@RequestMapping("users_A")
public class Controller02_A {

    //@RequestMapping("users")提前；method = RequestMethod.POST 优化为 @PostMapping
    //@RequestMapping(value = "users",method = RequestMethod.POST)
    @PostMapping
    //@ResponseBody 此类中所有方法都使用此注解，因此将其提前
    public String save(@RequestBody User user){
        System.out.println(RequestMethod.POST + "请求方式，保存User ： " + user);
        return "收到！";
    }

    //@RequestMapping("users")提前；method = RequestMethod.PUT 优化为 @PutMapping
    //@RequestMapping(value = "users", method = RequestMethod.PUT)
    @PutMapping
    //@ResponseBody 此类中所有方法都使用此注解，因此将其提前
    public String update(@RequestBody User user){
        System.out.println(RequestMethod.PUT + "请求方式，修改User ： " + user);
        return "收到！";
    }

    //@RequestMapping("users")提前；method = RequestMethod.DELETE 优化为 @DeleteMapping
    //@RequestMapping(value = "users/{id}", method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    //@ResponseBody 此类中所有方法都使用此注解，因此将其提前
    public String delete(@PathVariable String id){
        System.out.println(RequestMethod.DELETE + "请求方式，通过id "+ id +" 删除");
        return "收到！";
    }

    //@RequestMapping("users")提前；method = RequestMethod.GET 优化为 @GetMapping
    //@RequestMapping(value = "users/{id}", method = RequestMethod.GET)
    @GetMapping("/{id}")
    //@ResponseBody 此类中所有方法都使用此注解，因此将其提前
    public String query(@PathVariable String id){
        System.out.println(RequestMethod.GET + "请求方式，通过id "+ id +" 查询");
        return "收到！";
    }

    @GetMapping
    // 验证错误信息拦截
    public String queryThrowErr(){
        int i = 1 / 0;
        return "收到！";
    }

    @GetMapping("/math/{param}")
    // 验证自定义错误信息拦截
    public String mathThrowErr(@PathVariable Integer param) throws Exception {
        //验证业务异常
        if(0 == param){
            throw new BusinessException(ProjectErrorCode.BUSINESS_ZERO, "不允许为零！");
        }

        //验证系统异常
        if(9999 == param){
            throw new BusinessException(ProjectErrorCode.SYSTEM_ERR, "服务器繁忙，请稍后重试！");
        }

        //验证异常
        if(8888 == param) {
            throw new Exception("我报错了，你咬我啊！");
        }

        int i = 1 / param;
        return "收到！";
    }
}
